// https://api.douban.com/v2/book/isbn/9787536692930?apikey=0b2bdeda43b5688921839c8ecb20399b
const axios = require('axios')
const { mysql } = require('../qcloud')
// const { mysql: config } = require('../config')

module.exports = async (ctx) => {
		const { isbn, openid } = ctx.request.body
		if (isbn && openid) {
			const findRes = await mysql('books').select().where('isbn', isbn)
			if (findRes.length) {
				ctx.state = {
					code: -1,
					data: {
						msg: '图书已存在'
					}
				}
				return false
			}
			let res = await axios.get(`https://api.douban.com/v2/book/isbn/${isbn}?apikey=0b2bdeda43b5688921839c8ecb20399b`)
			const bookInfo = res.data
			const rate = bookInfo.rating.average
			const { title, image, alt, publisher, summary, price } = bookInfo
			const tags = bookInfo.tags.map(v => {
				return `${v.title} ${v.count}`
			}).join(',')
			const author = bookInfo.author.join(',')

			try {
					await mysql('books').insert({
							isbn, openid, rate, title, image, alt, publisher, summary, price, tags, author
					})
					// const DB = require('knex')({
					//   client: 'mysql',
					//   connection: {
					//     host: config.host,
					//     port: config.port,
					//     user: config.user,
					//     password: config.pass,
					//     database: config.db,
					//     charset: config.char,
					//     multipleStatements: true
					//   }
					// })
					// await DB('books').insert({
					//     isbn, openid, rate, title, image, alt, publisher, summary, price, tags, author
					// })
					ctx.state.data = {
							title,
							msg: 'success'
					}
			} catch (e) {
					ctx.state = {
							code: -1,
							data: {
									msg: '新增失败:' + e.sqlMessage
							}
					}
			}
		}
}
